<script lang="ts">
const defaultColors = [
  '#ffffff',
  '#f5222d',
  '#fa541c',
  '#fadb14',
  '#52c41a',
  '#1890ff',
  '#722ed1',
  '#8c8c8c',
  '#000000',
  ''
]
</script>
<script setup lang="ts">
import { throttle } from 'lodash-es'
import type { PropType } from 'vue'

const props = defineProps({
  value: {
    type: String
  },
  colors: {
    type: Array as PropType<string[]>,
    default: defaultColors
  }
})

const emits = defineEmits(['change'])
const onChange = throttle((color: string) => {
  emits('change', color)
}, 100)
</script>

<template>
  <div class="lego-color-picker">
    <div class="native-color-container">
      <input type="color" :value="props.value" @input="onChange($event.target?.value)" />
    </div>
    <ul class="picked-color-list">
      <li
        v-for="(color, index) in props.colors"
        :key="index"
        :class="`item-${index}`"
        @click.prevent="emits('change', color)"
      >
        <div :style="`background: ${color};`" class="color-item" v-if="color.startsWith('#')"></div>
        <div v-else class="color-item transparent-back"></div>
      </li>
    </ul>
  </div>
</template>

<style scoped lang="scss">
.lego-color-picker {
  display: flex;
}
.native-color-container {
  width: 40%;
}
.native-color-container input[type='color'] {
  width: 100%;
  cursor: pointer;
  height: 50px;
  border: 0;
  padding: 0;
  background-color: transparent;
}
.picked-color-list {
  padding: 0 0 0 5px;
  margin: 0;
  width: 60%;
  display: flex;
  list-style-type: none;
  flex-wrap: wrap;
  justify-content: space-between;
}
.picked-color-list li {
  flex: 1;
  width: 20%;
  min-width: 20%;
  max-width: 20%;
}
.color-item {
  padding: 3px;
  width: 20px;
  height: 20px;
  border-radius: 3px;
  margin-right: 5px;
  cursor: pointer;
  border: 1px solid #ccc;
}
.transparent-back {
  background: url('@/assets/img/transparent.png') no-repeat;
}
</style>
